package com.easymin.weixin.manager.impl;

import com.easymin.weixin.entity.WxBind;
import com.easymin.weixin.manager.WxBindManager;
import com.easymin.weixin.service.WxBindService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DefaultWxBindManager implements WxBindManager {

  @Autowired
  private WxBindService wxBindService;

  @Override
  public WxBind insert(WxBind wxbind) {
    wxBindService.insert(wxbind);
    return wxbind;
  }

  @Override
  public WxBind findByOpenIdAndAppKey(String openId, String appKey) {
    return wxBindService.findByOpenIdAndAppKey(openId, appKey);
  }

  @Override
  public WxBind findByPhoneAndAppKey(String phone, String appKey) {
    return wxBindService.findByPhoneAndAppKey(phone, appKey);
  }

  @Override
  public WxBind findOne(String phone, String openId, String appKey) {
    return wxBindService.findOne(phone, openId, appKey);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int delete(Long id, String appKey) {
    return wxBindService.delete(id, appKey);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int bind(String appKey, String phone, String openId, Long passengerId) {

    wxBindService.deleteByOpenId(appKey, openId);
    wxBindService.deleteByPhone(appKey, phone);

    WxBind wxBind = new WxBind();
    wxBind.setAppKey(appKey);
    wxBind.setPassengerId(passengerId);
    wxBind.setOpenId(openId);
    wxBind.setPhone(phone);
    return wxBindService.insert(wxBind);
  }

  /**
   * 注销用户
   * @param appKey 系统key
   * @param phone 电话
   * @param openId openId
   * @return
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void debind (String appKey, String phone, String openId) {
	  wxBindService.deleteByOpenId(appKey, openId);
	  wxBindService.deleteByPhone(appKey, phone);
  }
}
